package org.iks.gfs.business.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.RandomUtil;
import org.iks.gfs.business.vo.GfsFileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChunkService {

    @Value("${files.upload.path}")
    private String savePath;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private GfsFileService fileService;

    public String chunkFileToken(String fileName) {
        return fileService.saveGfsFile(fileName);
    }

    public List<String> chunkUpload(MultipartFile multipartFile, Integer index, String fileName, String chunkName, String chunkToken) throws IOException {
        String folderName = fileName.substring(0, fileName.indexOf(".") - 1);
        File folder = new File(savePath + "/" + folderName);
        if (!folder.exists()) {
            boolean res = folder.mkdirs();
        }
        if (chunkName == null) {
            chunkName = fileName + "-" + index;
        }
        File chunkFile = new File(folder.getPath() + "/" + chunkName);
        if (!chunkFile.exists()) {
            boolean newFile = chunkFile.createNewFile();
        }
        multipartFile.transferTo(chunkFile.getAbsoluteFile());
        File[] files = folder.listFiles();
        List<String> result = new ArrayList<>();
        if (files != null) {
            for (File file : files) {
                result.add(file.getName());
            }
        }
        GfsFileVo gfsFileVo = fileService.queryGfsFile(chunkToken);
        fileService.saveChunkFile(chunkName, index, gfsFileVo.getFileInfo().getId());
        return result;
    }

    public String mergeChunkFile(String fileName, List<String> chunkFiles) {
        String folderName = fileName.substring(0, fileName.indexOf(".") - 1);
        File folder = new File(savePath + "/" + folderName);
        List<File> files = new ArrayList<>();
        if (chunkFiles == null) {
            files = FileUtil.loopFiles(folder);
        }else {
            for (String chunkFile : chunkFiles) {
                files.add(new File(folder.getPath() + "/" + chunkFile));
            }
        }
        String extName = FileUtil.extName(fileName);
        String gfsName = RandomUtil.randomString(6) + "." + extName;
        File targetFile = new File(savePath + "/" + gfsName);
        FileWriter fileWriter = FileWriter.create(targetFile);
        for (File file : files) {
            byte[] bytes = FileUtil.readBytes(file);
            fileWriter.write(bytes, 0, bytes.length, true);
        }
        return gfsName;
    }


}
